﻿using System;
using System.Data;
using System.Data.SqlClient;
using Fuse8.DomainFramework.Common.Exceptions;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.DomainFramework.DataAccess
{
    internal class SqlDatabaseHelper
    {
         public static SqlCommand CreateCommandForType(string query, Type type, CommandType commandType = CommandType.Text)
         {
             var generic = typeof(IUnitOfWorkFactory<>).MakeGenericType(type);
             var factory = DependencyServiceLocator.Current.GetInstance(generic) as IUnitOfWorkFactory;
             if (factory == null)
             {
                 throw new UnitOfWorkFactoryNotDefinedException("Please register IUnitOfWorkFactory");
             }
             var unit = factory.GetSimple(false) as IDbUnitOfWork;

             if (unit == null)
             {
                 throw new UnitOfWorkNotDefinedException("Please register IUnitOfWorkFactory that create IDbUnitOfWork objects");
             }

             return new SqlCommand(query, unit.Connection, unit.Transaction){CommandType = commandType};
         }
    }
}